package top.kikt.book.core.handlers

import org.jsoup.nodes.Document
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.util.bookText
import top.kikt.book.util.metaContentWithProperty
import top.kikt.book.util.resolveBySrcUrl

class Bnn2 : BaseBookHandler() {

    override val host: String
        get() = "www.bnn2.com"

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        val name = document.metaContentWithProperty("og:title").trim()
        val desc = document.metaContentWithProperty("og:description").trim()
        val cover = document.metaContentWithProperty("og:image").trim()
        val author = document.metaContentWithProperty("og:novel:author").trim()
        return BookMetaEntity(name, url, url, author, cover, desc)
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val aList = document.select("#list-chapterAll dd a")

        return aList.mapIndexed { index, element ->
            val name = element.text()
            val url = element.attr("href").resolveBySrcUrl(menuUrl)
            ChapterMetaEntity(name, index, url, element)
        }
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        val doc = chapterMetaEntity.toDocument()
        val text = doc?.getElementsByClass("readcontent")?.bookText() ?: throw IllegalStateException("未找到内容")
        return chapterMetaEntity.toChapterMetaEntity(text)
    }

    override fun outputChapterTitle(): Boolean {
        return false
    }

    override fun watermark(): Map<Regex, String> {
        return mapOf(
            " ".toRegex() to "",
            "　".toRegex() to "",
            "<div .+>".toRegex() to "",
            "<script>.+</script>".toRegex() to "",
        )
    }
}